from fastapi import APIRouter
from pojo.pojo import *
from dbo.dbutil import *

app = APIRouter()

@app.post("/createUG")
async def createUG(data:UserGroup,user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    # print(data)
    if data.id is None:
        sql = '''
        INSERT INTO usergroup(title,userIdList,userId,`desc`)
        VALUES('{}','{}','{}','{}')
        '''.format(data.title,','.join(data.userIdList),user.id,data.desc)
    else:
        sql = '''
        UPDATE usergroup SET title='{}',userIdList='{}',`desc`='{}' WHERE id = '{}'
        '''.format(data.title,','.join(data.userIdList),data.desc,data.id)
    print(sql)
    data = Mysql().insertDB(sql)
    if data==0:
        rs["code"]=500
        rs["msg"]="创建问卷失败，程序员紧急处理中"
        return rs
    return rs


@app.post("/deleteUGByID")
async def deleteUGByID(data:UserGroup,user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    DELETE FROM usergroup
    WHERE id = '{}'
    '''.format(data.id)
    print(sql)
    data = Mysql().insertDB(sql)
    if data==0:
        rs["code"]=500
        rs["msg"]="删除问卷失败，程序员紧急处理中"
        return rs
    return rs

@app.post("/getUGByID")
async def getUGByID(user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    SELECT * FROM usergroup
    JOIN user ON user.id =  usergroup.userId
    WHERE usergroup.id = '{}'
    '''.format(user.id)
    print(sql)
    data = Mysql().selectDB(sql,'one')
    
    userInfoListData=[]
    if data["userIdList"]!='':
        sql = '''
        SELECT * FROM user
        WHERE 1=1 
        '''
        sql+='''
        AND user.id IN ({}) 
        '''.format(data["userIdList"])
        print(sql)
        userInfoListData = Mysql().selectDB(sql,'many')
    
    if data is None:
        rs["code"]=500
        rs["msg"]="查询失败，程序员修复中"
        return rs
    data.update({"userInfoList":userInfoListData})
    data["userIdList"] = [] if data["userIdList"]=='' else data["userIdList"].split(",")
    rs["data"]=data
    
    return rs



@app.post("/getUGListByUser")
async def getUGListByUser(user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    SELECT * FROM usergroup 
    JOIN user ON user.id =  usergroup.userId
    WHERE usergroup.userId = '{}'
    '''.format(user.id)
    print(sql)
    data = Mysql().selectDB(sql,'many')
    if data is None:
        rs["code"]=500
        rs["msg"]="查询失败，程序员修复中"
        return rs
    rs["data"]=data
    return rs

